<?php

require_once ('BaseAjaxModule.php');

class UserModule extends BaseAjaxModule {
	
	public function checkLoginTask()	{
		$user = $this->getUser();
		if ($user == null)
			$this->view->result = 0;
		else
			$this->view->result = 1;
	}
	
	public function viewInfoTask()	{
		$user = $this->getUser();
		if ($user == null)	{
			$this->view->setAjaxResponse($this->createErrorResult('Chưa đăng nhập!'));
			return;
		}
		$this->view->result = $user->getInfo();
	}

	public function logoutTask()	{
		//session
		$session = Joob_Session_Standard::getInstance();
		$session->setBehaviour(new Joob_Session_Behaviour_Namespace(null, 'Joob:Auth'));
		$session->set('id', null);
		$session->destroy();
		$this->view->result = 'success';
	}

	public function loginTask()	{
		if (!$this->getRequest()->hasParam('email') || !$this->getRequest()->hasParam('pwd'))	{
			$this->view->setAjaxResponse($this->createErrorResult('Chưa nhập email hoặc mật khẩu'));
			return;
		}
		
		$email = $this->getParam('email');
		
		//FIXME: password should be filtered as well?
		$passwd = $this->getParam('pwd', '', array(), true);
		
		$user = new Model_User();
		$user->email = $email;
		$user->pwd = $passwd;

		$result = $user->login();
		if ($result === true)	{
			$this->view->result = 'success';
			
			//session
			$session = Joob_Session_Standard::getInstance();
			$session->setBehaviour(new Joob_Session_Behaviour_Namespace(null, 'Joob:Auth'));
			$session->set('id', $user->id);
		} else {
			$this->view->setAjaxResponse($this->createErrorResult($result));
		}
	}
}

?>